//view层界面控制逻辑
define(['jquery','audioPlayer','h5player'],function($,audioPlayer,Player){
 //	==== 私有方法 ========================================================================	
	var screenW=$(window).width(),screenH=$(window).height();  //获取屏幕宽高	
	//给canvas动态分配等比例宽高
	function setCanvasWH(){
		var canvasH=$('canvas').height();
		$('canvas').css({
			width:canvasH*1.47763348
//			left:($(window).width()-$('canvas').width())/2
		});
	};
	//格式化时间方法
	 Number.prototype.formatTime=function(){
            var h=0,m=0,s=parseInt(this);
            if(s>60){
                m=parseInt(s/60);s=parseInt(s%60);
                if(m>60){
                    h=parseInt(m/60);m=parseInt(m%60);
                }
            }
//		前位补零
            var zero=function(v){
                return (v>>0)<10?"0"+v:v;
            };
            return [zero(h),zero(m),zero(s)].join(":");
        };

		//手机端菜单栏的隐藏与显示。----私有方法。
//		function showHideMenu(){
//			getMenu=$(".menu");
//			if(!getMenu.is(":hidden")){  //如果显示着
//                  	setTimeout(function(){getMenu.fadeOut(1000)},2000);  //2秒后隐藏
//                 }
//					
//					getMenu.click(function(){					
//                        getMenu.stop(true,true);
//                        getMenu.show();
//                        setTimeout(function(){getMenu.fadeOut(1000)},2000);  //2秒后隐藏
//					});
//		}
		

//=======对象==========================
	var View={
		//				http://7sbr2j.com2.z0.glb.qiniucdn.com/471520150727161155
		//				http://7sbr2j.com2.z0.glb.qiniucdn.com/319820150728111318		3670
		//				http://7sbr2j.com2.z0.glb.qiniucdn.com/444520150728142045		3675
		//				http://7sbr2j.com2.z0.glb.qiniucdn.com/360720150728165327		3682
		//				http://192.168.0.183:8020/newH5Player/testvideo/333320150804095533
		//				http://192.168.0.183:8020/newH5Player/testvideo/581920150807133659
		//				http://192.168.0.183:8020/newH5Player/testvideo/644120150807134721
		//				http://192.168.0.183:8020/newH5Player/testvideo/259020150810154310
		//				http://192.168.0.183:8020/newH5Player/testvideo/698820150810165628
		//				http://192.168.0.183:8020/newH5Player/testvideo/142920150811105029
		player : new Player('frontCanvas','audio',"http://7sbr2j.com2.z0.glb.qiniucdn.com/558220150618161942"),
		init:function(){ //初始化
			setCanvasWH();		
			
			window.onresize=function(){
				setCanvasWH();
			};
			this.player.init();
			//加载资源成功
			this.player.on('loadRsSuccess',function(){
				alert("加载资源成功");
			});
			
			//加载资源失败
			this.player.on('loadRsError',function(err){
				alert("加载资源失败:" + err.message);
			});
			
			//加载资源失败
			this.player.on('play',function(err){
				if(!this.isPlaying()){
					$('#playerCtrl .audioplayer-playpause').attr( 'title', 'Play' ).find( 'a' ).html( 'Play' );
					$('#playerCtrl').removeClass( 'audioplayer-playing' ).addClass( 'audioplayer-stopped' );
				}else{
					$('#playerCtrl .audioplayer-playpause').attr( 'title', 'Pause' ).find( 'a' ).html( 'Pause' );
					$('#playerCtrl').addClass( 'audioplayer-playing' ).removeClass( 'audioplayer-stopped' );
				}
			});
			
			//加载资源失败
			this.player.on('pause',function(err){
				if(!this.isPlaying()){
					$('#playerCtrl .audioplayer-playpause').attr( 'title', 'Play' ).find( 'a' ).html( 'Play' );
					$('#playerCtrl').removeClass( 'audioplayer-playing' ).addClass( 'audioplayer-stopped' );
				}else{
					$('#playerCtrl .audioplayer-playpause').attr( 'title', 'Pause' ).find( 'a' ).html( 'Pause' );
					$('#playerCtrl').addClass( 'audioplayer-playing' ).removeClass( 'audioplayer-stopped' );
				}
			});
			
			//=========================进度条audio=====================
			var theAudio	  =$("audio").get(0),
				thePlay       =$('#playerCtrl'),
				playPause     =$(".audioplayer-playpause"),
				barLoaded	  =$(".audioplayer-bar-loaded"),
				barPlayed	  =$(".audioplayer-bar-played"),
				currentTime   =$(".audioplayer-time-current"),
				timeDuration  =$(".audioplayer-time-duration"),
				theBar        =$(".audioplayer-bar"),
				volumeAdjuster=$(".audioplayer-volume-adjust > div"),
				volumeButton  =$(".audioplayer-volume-button"),
			    isTouch		  = 'ontouchstart' in window,
				eStart		  = isTouch ? 'touchstart'	: 'mousedown',
				eMove		  = isTouch ? 'touchmove'	: 'mousemove',
				eEnd		  = isTouch ? 'touchend'	: 'mouseup',
				eCancel		  = isTouch ? 'touchcancel'	: 'mouseup';
			
			//播放与暂停
			playPause.on('click',function(){
				if(this.player.isPlaying()){
					playPause.attr( 'title', 'Play' ).find( 'a' ).html( 'Play' );
					thePlay.removeClass( 'audioplayer-playing' ).addClass( 'audioplayer-stopped' );
					this.player.pause();
				}else{
					playPause.attr( 'title', 'Pause' ).find( 'a' ).html( 'Pause' );
					thePlay.addClass( 'audioplayer-playing' ).removeClass( 'audioplayer-stopped' );
					this.player.play();
				}
				if( this.player.getCurrentTime()==this.player.getDuration() ){
					thePlay.removeClass( 'audioplayer-playing' ).addClass( 'audioplayer-stopped' );
				}
			}.bind(this));
			
			//时间转换，调节时间
			var secondsToTime = function( secs ){
				var hoursDiv = secs / 3600, hours = Math.floor( hoursDiv ), minutesDiv = secs % 3600 / 60, minutes = Math.floor( minutesDiv ), seconds = Math.ceil( secs % 3600 % 60 );
				if( seconds > 59 ) { seconds = 0; minutes = Math.ceil( minutesDiv ); }
				if( minutes > 59 ) { minutes = 0; hours = Math.ceil( hoursDiv ); }
				return ( hours == 0 ? '' : hours > 0 && hours.toString().length < 2 ? '0'+hours+':' : hours+':' ) + ( minutes.toString().length < 2 ? '0'+minutes : minutes ) + ':' + ( seconds.toString().length < 2 ? '0'+seconds : seconds );
			};
			
			var adjustCurrentTime = function( e ){
				theRealEvent		 = isTouch ? e.originalEvent.touches[ 0 ] : e;
				this.player.setCurrentTime(Math.round( ( this.player.getDuration() * ( theRealEvent.pageX - theBar.offset().left ) ) / theBar.width() ));
			}.bind(this);
			
			//音量设置
			
			var adjustVolume = function( e ){
				theRealEvent	= isTouch ? e.originalEvent.touches[ 0 ] : e;
				theAudio.volume = Math.abs( ( theRealEvent.pageY - ( volumeAdjuster.offset().top + volumeAdjuster.height() ) ) / volumeAdjuster.height() );
		 		volumeAdjuster.find( 'div' ).height( theAudio.volume + '%' );
			}.bind(this);
			
			var volumeDefault = theAudio.volume;
			volumeButton.on( 'click', function(){
					if( thePlay.hasClass( 'audioplayer-muted' ) )
					{
						thePlay.removeClass( 'audioplayer-muted' );
						theAudio.volume = volumeDefault;
					}
					else
					{
						thePlay.addClass( 'audioplayer-muted' );
						volumeDefault = theAudio.volume;
						theAudio.volume = 0;
					}
			});
			
			theAudio.addEventListener( 'volumechange', function(){
				volumeAdjuster.find( 'div' ).height( theAudio.volume * 100 + '%' );
				if( theAudio.volume > 0 && thePlay.hasClass( 'audioplayer-muted' ) ) thePlay.removeClass( 'audioplayer-muted' );
				if( theAudio.volume <= 0 && !thePlay.hasClass( 'audioplayer-muted' ) ) thePlay.addClass( 'audioplayer-muted' );
			});

			//缓冲条设置，初始时间，结束时间
			var interval=setInterval( function(){
				barLoaded.width(this.player.getBufferedPercent()+'%');
				barPlayed.width(this.player.getCurrentTimePercent()+'%');
				currentTime.html( secondsToTime( this.player.getCurrentTime() ) );
				timeDuration.html( secondsToTime( this.player.getDuration() ) );				
			}.bind(this), 1000 );
			
			//触摸调用
			theBar.on( eStart, function( e ){
					adjustCurrentTime( e );
					theBar.on( eMove, function( e ) { adjustCurrentTime( e ); } );
				})
				.on( eCancel, function(){
					theBar.unbind( eMove );
				});
			
			volumeAdjuster.on( eStart, function( e ){
					adjustVolume( e );
					volumeAdjuster.on( eMove, function( e ) { adjustVolume( e ); } );
				})
				.on( eCancel, function(){
					volumeAdjuster.unbind( eMove );
				});
			
		},
		changePlayPic:function(flag){ //改变播放按钮状态：0暂停，1播放
			if(flag==0){
				//显示暂停图片
			}else{
				//显示播放图片
			}
		},		
		showAlert:function(msg){ //显示提示信息方法--如：“加载中...”等
			alert(msg);
		},
		setStatus:function(status){//设置状态的方法
			$('.statusDiv').text(status);
		},
		getStatus:function(){//获取状态的方法
			return $('.statusDiv').text();
		},
		setCurrentTime:function(c_time){ //设置当前时间
			$('.currentTime').text(c_time.formatTime());
		},
		setTotalTime:function(t_time){ //设置总时间
			$('.totalTime').text(t_time.formatTime());
		},
		
		//状态栏点击出现/消失
	   showStatusbar:function (event){
			var isTouch= ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch;
			event.preventDefault(); //阻止触摸事件的默认行为，即阻止滚屏	
			if(isTouch){	
				$(".playArea").click(function(){
					var display=$(".menu").css("display");
					
					if(display=='block'){
						$(".menu").hide();
					}else if(display=='none'){
						$(".menu").show();
						
						setTimeout(function(){
						$(".menu").hide();
						},5000);
					}
				});
				
//				if($(".menu").css("display") != "none"){
//					setTimeout(function(){
//						$(".menu").hide();
//					},6000);
//				}
			}			
		},
//		//移动端滑动，进度条快进或快退
		handleEvent:function(event){
			var touch= ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch;
			event.preventDefault(); //阻止触摸事件的默认行为，即阻止滚屏
			var theAudio=$("audio").get(0);
			var barWidth=$(".audioplayer-bar").width();
		
			function start(event){
				var sTouch=event.touches[0];
				startPos={x:sTouch.pageX,y:sTouch.pageY};
			}
			
			function move(event){
				var mTouch=event.targetTouches[0];
				endPos={x:mTouch.pageX-startPos.x,y:mTouch.pageY-startPos.y};
				
				if(endPos.x > 0 && endPos.y<30 ){   //右滑
					theAudio.currentTime +=Math.abs( 0.06*theAudio.duration * endPos.x / barWidth );
				}else if(endPos.x < 0 && endPos.y<30){
					theAudio.currentTime -=Math.abs( 0.06*theAudio.duration * endPos.x / barWidth );
				}
			}
			$(function(){
				document.addEventListener("touchstart", start, false);
				document.addEventListener("touchmove", move, false);
			})
	
		}
	}
	return View;
});